<template>
    <div class="marketing_group">
        <!-- 新增操作 -->
        <div class="marketing_group_top">
            <el-row class="marketing_group_header" :gutter="10">
                <el-col v-for="{ groupTypeName, groupType, groupTypeDesc } in groupTypeList" :key="groupType" :span="8">
                    <div class="marketing_group_header_item">
                        <div>
                            <h3>
                                {{ groupTypeName }}
                                <el-tooltip v-if="groupType == 4" effect="dark" placement="right">
                                    <template #content
                                        >新客：商城内没有订单的客户，或仅拥有全额退款、已关闭<br />待付款的订单</template
                                    >
                                    <el-icon><Warning /></el-icon>
                                </el-tooltip>
                            </h3>
                            <p>{{ groupTypeDesc }}</p>
                        </div>
                        <el-button type="primary" @click="addRouterHandler(groupType)" v-auth="'group_list:create'"
                            >立即新增</el-button
                        >
                    </div>
                </el-col>
            </el-row>
            <!-- tab -->
            <el-tabs v-model="form.activityType" @tabChange="tabHandler">
                <el-tab-pane
                    v-for="{ groupTypeName, groupType } in groupTypeList"
                    :key="groupType"
                    :label="groupTypeName"
                    :name="groupType"></el-tab-pane>
            </el-tabs>
        </div>
        <div class="marketing_group_bottom">
            <!-- 查询 -->
            <div class="zw-form-layout">
                <el-form ref="formRef" :model="form" label-width="auto">
                    <el-row :gutter="24">
                        <!-- todo:根据json生成表单 -->
                        <!-- <el-col :span="8" v-for="{ name, label, component, attrs } in formDomList" :key="name">
                        <el-form-item :label="label" :prop="name">
                            <component v-model="form[name]" :is="component" clearable v-bind="attrs"></component>
                        </el-form-item>
                    </el-col> -->
                        <el-col :span="6">
                            <el-form-item label="活动名称" prop="activityName">
                                <el-input v-model="form.activityName" clearable placeholder="请输入活动名称"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="活动状态" prop="activityStatus">
                                <el-select v-model="form.activityStatus" clearable placeholder="请选择状态">
                                    <el-option
                                        v-for="item in activityStatusList"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item label="活动时间" prop="activityAt">
                                <el-date-picker
                                    v-model="form.activityAt"
                                    type="datetimerange"
                                    range-separator="至"
                                    :default-time="defaultTime"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="5" class="zw-form-btns">
                            <el-button type="primary" @click="searchHandler" v-auth="'group_list:query'"
                                >查询</el-button
                            >
                            <el-button plain @click="resetHandler">清空</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <!-- 列表 -->
            <el-table :data="tableList" :stripe="true">
                <el-table-column v-for="{ prop, ...rest } in tableColumns" :key="prop" :prop="prop" v-bind="rest">
                    <template
                        v-if="['activityTime', 'activityName', 'operations', 'realStatusName'].includes(prop)"
                        #default="{ row }">
                        <template v-if="prop === 'activityTime'">
                            {{ row.activityStartTime }}至<br />{{ row.activityEndTime }}
                        </template>
                        <template v-if="prop === 'activityName'">
                            <!-- <el-link type="primary" class="custom-el-link" @click="nameRouteHandler(row, 'group')">{{
                                row.activityName
                            }}</el-link> -->
                            <div class="custom-el-link">
                                <span @click="nameRouteHandler(row, 'group')">{{ row.activityName }}</span>
                            </div>
                        </template>
                        <template v-if="prop === 'realStatusName'">
                            <span :class="`custom-status-${row.realStatus}`">{{ row.realStatusName }}</span>
                        </template>
                        <template v-if="prop === 'operations'">
                            <el-button
                                v-for="{ label, fn, ref, auth } in row.operations"
                                :key="label"
                                @click="fn(row, ref)"
                                size="small"
                                :ref="el => setItemRef(el, `${ref}${row.id}`)"
                                class="table-button"
                                v-auth="auth"
                                >{{ label }}</el-button
                            >
                        </template>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div style="margin-top: 15px">
                <Pagination
                    :total="totalCount"
                    :page-size="form.perPage"
                    :current-page="form.page"
                    @sizeChange="changeSizeHandler"
                    @pageChange="changePageHandler" />
            </div>
        </div>
        <!-- popover弹窗 -->
        <el-popover
            popper-class="custom-group-popover-class not-close"
            ref="popoverRef"
            :virtual-ref="buttonRef"
            placement="top"
            trigger="click"
            virtual-triggering
            :width="currentRow.ref === 'spreadButtonRef' ? 400 : 240"
            :visible="popoverVisible">
            <!-- todo:不同的内容 -->
            <div
                class="custom-group-popover-class-main"
                v-click-outside="onClickOutside"
                v-if="['endButtonRef', 'removeButtonRef'].includes(currentRow.ref)">
                <template v-if="currentRow.ref == 'endButtonRef'">
                    <h3>
                        <el-icon class="custom-icon"><WarningFilled /></el-icon>你确定要结束吗？
                    </h3>
                    <!-- 未开始状态结束时确认提醒 -->
                    <p v-if="currentRow.realStatus == 1">结束后活动将无法启用</p>
                    <!-- 进行中状态结束时确认提醒 -->
                    <p v-else>结束后活动即刻结束，未成团订单将自动关闭并退款</p>
                </template>
                <!-- 删除 -->
                <h3 style="margin-bottom: 16px" v-if="currentRow.ref == 'removeButtonRef'">
                    <el-icon class="custom-icon"><WarningFilled /></el-icon>你确定要删除吗？
                </h3>
                <div style="text-align: right">
                    <el-button size="small" @click="popoverVisibleHandler()">取消</el-button>
                    <el-button size="small" type="primary" @click="popoverConfirmHandler()">确定</el-button>
                </div>
            </div>
            <SpreadBox
                v-if="popoverVisible && currentRow.ref === 'spreadButtonRef'"
                :path="path"
                :params="params"
                :downloadName="downloadName"
                :popoverFn="popoverVisibleHandler" />
        </el-popover>
    </div>
</template>

<script setup name="marketingGroup">
import { ref, unref, reactive, computed, onMounted, onUnmounted, onActivated, onDeactivated, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { ClickOutside as vClickOutside } from 'element-plus';
import request from '@/request/index';
import constants from '@/commons/constants';
import { packSelectObjUtil } from '@/commons/utils';
import { setLayout, resetLayout } from '@/hooks/layout';
import Pagination from '@/components/Pagination.vue';
import { cloneDeep } from '../../../../commons/utils';
import store from '@/store/index';
import SpreadBox from '@/components/SpreadBox.vue';

const router = useRouter();
const activityStatusList = reactive(packSelectObjUtil(constants.GROUP_STATUS_OPTIONS));

// todo:优化代码结构
// 顶部新增和Tabs Dom
let groupTypeList = reactive([]);
const form = reactive({
    page: 1,
    perPage: 10,
    activityType: 3, // 活动类型 3-普通拼团 4-老带新 5-阶梯拼团
    activityName: '', // 活动名
    activityStatus: 0, // 活动状态 1-未开始 2-进行中 3-已结束 0-全部
    activityAt: [], // 开始结束时间
    isShowEnd: 1 // 是否显示结束状态 1-显示 2-不显示
});
let formClone = reactive(null);
const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)];
const formDomList = [
    {
        name: 'activityName',
        label: '活动名称',
        component: 'el-input',
        attrs: {
            placeholder: '请输入活动名称'
        }
    },
    { name: 'activityStatus', label: '活动状态', component: 'el-input', attrs: { placeholder: '请选则状态' } },
    { name: 'activityAt', label: '活动时间', component: 'el-input' }
]; // todo: 之后有时间做成json生成的表单
const formRef = ref(null);
const totalCount = ref(0);
let tableList = reactive([]);

// popover ref
let popoverVisible = ref(false);
const itemRefs = {};
const setItemRef = (el, key) => {
    if (el) {
        itemRefs[key] = el;
    }
};
const popoverRef = ref(null);
const buttonRef = ref(null);
let currentRow = reactive({ ref: null, id: null, status: null });

const tableColumns = computed(() => {
    const baseTableColumns = [
        { label: '活动名称', prop: 'activityName', showOverflowTooltip: true, minWidth: '220' },
        { label: '活动时间', prop: 'activityTime', minWidth: '220' },
        { label: '活动状态', prop: 'realStatusName', width: '110' },
        { label: '成团订单数', prop: 'groupOrderNum', width: '110' },
        { label: '成团客户数', prop: 'groupCustNum', width: '110' },
        { label: '销售额（元）', prop: 'saleAmount', width: '110' },
        { label: '操作', prop: 'operations', width: '270', fixed: 'right' }
    ];
    if (form.activityType == 4) {
        // 老带新的表格列
        const columns = [...baseTableColumns];
        columns.splice(5, 0, { label: '参团新客户数', prop: 'groupNewCustNum' });
        return columns;
    }
    return baseTableColumns;
});

const nameRouteHandler = ({ id, marketGoods }, type) => {
    const { shopId, goodsId } = marketGoods?.[0] || {};
    const useAuth = store.useAuthStore();
    const permissions = useAuth.permissions;
    const code = 'group_list:query';
    if (!permissions.has(code)) {
        ElMessage({
            type: 'error',
            message: '当前用户没有查看权限'
        });
        return false;
    }
    const { href } = router.resolve({
        path: '/marketing/group/detail',
        query: {
            id,
            shopId,
            goodsId,
            type
        }
    });
    window.open(href, '_blank');
};
const addRouterHandler = type => {
    const typeNames = {
        3: 'add',
        4: 'new',
        5: 'ladder'
    };
    form.activityType = type;
    routerHandler(typeNames[type]);
};
const routerHandler = (type, query) => {
    const paths = {
        add: '/marketing/group/add',
        new: '/marketing/group/newAdd',
        ladder: '/marketing/group/ladderAdd'
    };
    router.push({ path: paths[type], query });
};
// 以下有时间抽离成公共查询js
/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    queryCouponListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.perPage = perPage;
    queryCouponListHandler();
};
/**
 * 分页查询
 */
const queryCouponListHandler = async () => {
    const res = await request('spellGroupList', form);
    const list = (res.data.list || []).map(item => {
        // todo: 根据不同状态显示不同按钮
        item.activityTime = `${item.activityStartTime}至${item.activityEndTime}`;
        item.realStatusName = item.activityStatusName.realStatusName;
        item.realStatus = item.activityStatusName.realStatus;
        item.saleAmount = item.saleAmount / 100;
        const btns = [
            { label: '编辑', fn: editHandler, ref: 'editButtonRef', auth: 'group_list:edit' },
            { label: '推广', fn: spreadHandler, ref: 'spreadButtonRef', auth: 'group_list:spread' },
            { label: '结束', fn: endHandler, ref: 'endButtonRef', auth: 'group_list:end' },
            { label: '数据', fn: dataHandler, ref: 'dataButtonRef', auth: 'group_list:query' },
            { label: '删除', fn: removeHandler, ref: 'removeButtonRef', auth: 'group_list:delete' }
        ];
        if (item.realStatus == 1) {
            item.operations = [btns[0], btns[1], btns[2]];
        } else if (item.realStatus == 2) {
            item.operations = [btns[0], btns[1], btns[3], btns[2]];
        } else if (item.realStatus == 3) {
            item.operations = [btns[3], btns[4]];
        }
        return item;
    });
    tableList.length = 0;
    tableList.push(...list);
    totalCount.value = res.data.totalCount;
};
/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
    searchHandler();
    formClone = cloneDeep(form);
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.page = 1;
    formClone = cloneDeep(form);
    queryCouponListHandler();
};
/** 按钮组操作 */
const popoverHandler = ({ id, realStatus, activityName, codeUrl }, ref) => {
    buttonRef.value = itemRefs[`${ref}${id}`];
    currentRow.ref = ref;
    currentRow.id = id;
    currentRow.realStatus = realStatus;
    currentRow.activityName = activityName;
    currentRow.codeUrl = codeUrl;

    nextTick(() => {
        popoverVisible.value = true;
    });
};
// 编辑
const editHandler = row => {
    // todo:activityType
    const editType = {
        3: 'edit',
        4: 'newEdit',
        5: 'ladderEdit'
    };
    router.push({
        path: `/marketing/group/${editType[row.activityType]}`,
        query: {
            id: row.id
        }
    });
};
// 推广
let path = ref();
let params = ref();
let downloadName = ref();
const spreadHandler = async (row, ref) => {
    const goodsId = row?.marketGoods?.[0]?.goodsId;
    const shopId = row?.marketGoods?.[0]?.shopId;
    path.value = 'pages-cart/good/index';
    params.value = `goodsId=${goodsId}&shopId=${shopId}&activityId=${row.id}`;
    downloadName.value = row?.activityName;
    popoverHandler(row, ref);
};
// 结束
const endHandler = (row, ref) => {
    popoverHandler(row, ref);
};
// 数据
const dataHandler = row => {
    nameRouteHandler(row, 'statistics');
};
// 删除
const removeHandler = (row, ref) => {
    popoverHandler(row, ref);
};
// 点击popover外部
const onClickOutside = el => {
    popoverVisibleHandler();
};
// 控制popover展示隐藏
const popoverVisibleHandler = (visible = false) => {
    popoverVisible.value = visible;
};
// popover确定
const popoverConfirmHandler = async () => {
    await request(`spellGroup${currentRow.ref === 'removeButtonRef' ? 'Del' : 'End'}`, { id: currentRow.id });
    popoverVisibleHandler();
    searchHandler();
    ElMessage({
        type: 'success',
        message: '操作成功'
    });
};

//切换tab筛选
const tabHandler = () => {
    searchHandler();
};

// 获取顶部卡片
const getGroupType = async () => {
    const res = await request('spellGroupType');
    groupTypeList.length = 0;
    groupTypeList.push(...res.data);
};
const getAllData = () => {
    getGroupType();
    searchHandler();
};

// onMounted(() => {
//     // getAllData();
//     setLayout();
// });
// onUnmounted(() => {
//     resetLayout();
// });
// 监听页面可见性
const visibilityChange = () => {
    // 用户离开了当前页面
    if (document.visibilityState === 'hidden') {
    }
    // 用户打开或回到页面
    if (document.visibilityState === 'visible') {
        queryCouponListHandler();
    }
};
onActivated(() => {
    Object.keys(formClone || {})?.forEach(key => {
        form[key] = formClone[key];
    });
    getAllData();
    setLayout();
    document.addEventListener('visibilitychange', visibilityChange);
});
onDeactivated(() => {
    resetLayout();
    document.removeEventListener('visibilitychange', visibilityChange);
});
</script>
<style lang="scss">
.custom-group-popover-class {
    padding: 0px !important;
    &-main {
        padding: 16px !important;
    }
    h3,
    p {
        margin: 0;
    }
    h3 {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #33302d;
        display: flex;
        .custom-icon {
            width: 14px;
            height: 14px;
            margin-right: 9px;
            color: #faad14;
            margin-top: 2px;
        }
    }

    p {
        padding-left: 23px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #969696;
        line-height: 16px;
        margin: 8px 0 16px;
    }

    p + div {
        text-align: right;
    }
}
</style>
<style lang="scss" scoped>
$colors: #cccccc, #2fb6e4, #ff4a1a;

.marketing_group {
    &_top {
        background-color: #fff;
        padding: 24px 24px 0;
        margin-bottom: 16px;
    }
    &_header {
        margin-bottom: 20px;
        overflow: hidden;
        :deep {
            .el-col-8 {
                overflow: hidden;
                padding-bottom: 512px;
                margin-bottom: -500px;
                &:last-of-type {
                    & > div {
                        margin-right: 0;
                    }
                }
            }
        }
        &_item {
            position: relative;
            background: #fff6ef;
            display: flex;
            margin-right: 15px;
            align-items: center;
            justify-content: space-between;
            padding: 24px;
            overflow: hidden;
            padding-bottom: 512px;
            margin-bottom: -500px;

            h3,
            p {
                margin: 0;
            }
            h3 {
                font-size: 16px;
                font-family: PingFangSC-Medium, PingFang SC;
                font-weight: 500;
                color: #33302d;
                display: flex;
                align-items: center;
                :deep(.el-icon) {
                    color: #33302d;
                    margin-left: 4px;
                }
            }
            p {
                margin-top: 16px;
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #666666;
                line-height: 20px;
            }
            & > div {
                margin-right: 118px;
                /* min-height: 78px; */
            }
            :deep(.el-button) {
                position: absolute;
                right: 24px;
                top: 24px;
            }
        }
    }
    :deep(.el-tabs__item) {
        font-size: 16px !important;
    }
    :deep {
        .el-table {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #33302d;
            .el-button--small {
                font-size: 12px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #33302d;
                border: 1px solid #eaeaea;
            }
            .el-button--small + .el-button--small {
                margin-left: 8px;
            }
        }
        .el-tabs__nav-wrap {
            margin-bottom: -15px;
            &::after {
                height: 0;
            }
        }
        .el-table .el-table__cell {
            padding: 20px 0;
        }

        .el-table th.el-table__cell {
            padding: 12px 0;
        }

        .el-table th.el-table__cell {
            font-size: 14px;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #33302d;
        }
    }
    &_bottom {
        padding: 24px;
        background-color: #fff;
    }
    .zw-form-layout {
        background: #f9f9f9;
        border: 1px solid #eaeaea;
        margin-bottom: 24px;
    }
    .not-started {
        color: #aaa;
    }

    .custom-el-link {
        color: rgb(255, 107, 0);
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
        span {
            cursor: pointer;
            &:hover {
                text-decoration: underline;
            }
        }
    }

    @for $i from 1 to 4 {
        .custom-status-#{$i} {
            position: relative;
            padding-left: 14px;
            &::before {
                content: '';
                position: absolute;
                width: 8px;
                height: 8px;
                border-radius: 50%;
                left: 0px;
                top: 50%;
                transform: translateY(-50%);
                background: nth($colors, $i);
            }
        }
    }
}
</style>
